<?php

/**
 * @classname 项目公共类
 * @classaccess private
 * @decription 项目程序的公共类
 * @author 张旭刚
 * @updateTime 2020年05月12日
 */

namespace api\controllers;

use Yii;
use api\models\Members;
use api\models\Membertokens;

class PublicController extends \common\controllers\CommonController {

    public $enableCsrfValidation;
    protected $debug;
    protected $member;
    protected $memberKey;
    protected $isLogin;
    protected $token;

    public function __construct($id, $module, $config = array()) {
        parent::__construct($id, $module, $config);
        $this->enableCsrfValidation = false;
        $this->getDebug();
        $this->getHeaders();
        $this->checkLogin();
    }
    
    /**
     * 获得图片地址地址
     * @param type $pic
     * @return type
     */
    protected function getFace($pic) {
        if (empty($pic)) {
            return Yii::$app->params['pic'] . 'nocover.jpg';
        } else {
            $fileName = basename($pic);
            $picRealPath = $this->setting('pic_realpath_path');
            $realPath = $picRealPath . $fileName;
//            echo $realPath;
            if (!file_exists($realPath)) {
                return Yii::$app->params['pic'] . 'nocover.jpg';
            } else {
                return Yii::$app->params['pic'] . $fileName;
            }
        }
    }
    
    /**
     * 设置Headers
     */
    private function getHeaders(){
        $this->headers = Yii::$app->request->headers;
        $url = $this->getUrl();
        if($url !== '/site/guid' && $url !== '/' && (!isset($this->headers['guid']) || empty($this->headers['guid']))){
            return $this->renderJson(['code' => 0, 'msg' => 'GUID不存在', 'result' => false, 'errorCode' => 101001]);
        }
        $this->guid = $this->headers['guid'];
        
    }
    
    /**
     * 检查是否登录了
     */
    private function checkLogin(){
        //判断是否需要登录
        $this->isLogin = false;
        $notLogins = $this->getNotLogins();
        $action = $this->getAction();
        $this->token = isset($this->headers['token']) ? $this->headers['token'] : '';
        if(!in_array($action, $notLogins)){
            if(empty($this->token)){
                return $this->renderJson(['code' => 0, 'msg' => '登录失败或超时', 'result' => false, 'errorCode' => 101004]);
            }
            $tokens = $this->getTokens();
            $this->currentMember($tokens['memberKey']);
        }
    }
    
    private function currentMember($memberKey){
        $userhashKey = $this->setting('wx_userinfos_key');
        $member = Members::find()->where(['memberKey' => $memberKey])->asArray()->one();
        if(empty($member)){
            return $this->renderJson(['code' => 0, 'msg' => '登录失败或超时', 'result' => false, 'errorCode' => 101003]);
        }
        $this->member = $member;
        $this->memberKey = $member['memberKey'];
        $this->isLogin = true;
    }


    /**
     * Tokens
     */
    private function getTokens(){
        $tokens = Membertokens::find()->where(['token' => $this->headers['token']])->asArray()->one();
        // $this->renderJson([$tokens]);
        $long = time() - $tokens['ctime'];
        $tokenLong = intval($this->setting('user_login_token_limit_long'));
        if($long > $tokenLong){
            return $this->renderJson(['code' => 0, 'msg' => '登录失败或超时', 'result' => false, 'errorCode' => 101002]);
        }
        return $tokens;
    }

    /**
     * 获得不需要登录的Action
     */
    private function getNotLogins(){
        $str = $this->setting('api_not_login_actions');
        $notLogins = explode(',', $str);
        return $notLogins;
    }

    /**
     * 获取当前Action
     * @return type
     */
    private function getAction(){
        $action = Yii::$app->request->url;
        if($action == '/'){
            return 'site/index';
        }
        $str = substr($action, 1, strlen($action));
        $strs = explode('?', $str);
        $s = explode('&', $strs[0]);
        return $s[0];
    }
    
    /**
     * 设置debug状态
     */
    private function getDebug(){
        $debug = $this->setting('api_debug');
        $this->debug = empty($debug) ? $this->debug = 'no' : $debug;
    }
    
    /**
     * 设置Token 暂时无用
     * @param type $member
     * @return type
     */
    protected function setToken($member){
        $tokenSalt = $this->setting('token_salt');
        $tokenLong = $this->setting('token_expire_time_long');
        $m = Tokens::findOne(['memberId' => $member->memberId]);
        if(empty($m)){
            $m = new Tokens();
            if($this->loginType == 'mobile'){$m->mobile = $member->mobile;}elseif($this->loginType == 'email'){$m->email = $member->email;}
            $m->wxopenid = $member->wxopenid;
            $m->memberId = $member->memberId;
            $m->token = md5($tokenSalt.'_'.$member->memberId.'_'.$member->mobile.'_'.$member->email.'_'.$member->wxopenid.'_'.$tokenSalt.'_'.time());
            $m->refreshToken = md5($tokenSalt.'_'.$member->memberId.'_'.$tokenSalt.'_'.time());
            $m->ctime = time();
            $m->save(false);
        }else{
            $long = time() - $m->ctime;
            if($long > $tokenLong){
                $m->token = md5($tokenSalt.'_'.$member->memberId.'_'.$member->mobile.'_'.$member->email.'_'.$member->wxopenid.'_'.$tokenSalt.'_'.time());
                $m->refreshToken = md5($tokenSalt.'_'.$member->memberId.'_'.$tokenSalt.'_'.time());
                $m->ctime = time();
                $m->save(false);
            }
        }
        return ['token' => $m->token, 'refreshToken' => $m->refreshToken, 'expireTime' => (int)$tokenLong, 'startTime' => $m->ctime];
    }

}
